package com.zbx.springcloud.controller;


import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import com.zbx.springcloud.pojo.Dept;
import com.zbx.springcloud.service.DeptService;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;

/**
 * @description:
 * @author: zbxComputer
 * @time: 2023/5/23 20:05
 */
//提供restful服务
@RestController
@RequestMapping("/dept")
public class DeptController {

    @Resource
    private DeptService deptService;

    @Resource
    private DiscoveryClient client;


    @PostMapping("/add")
    public boolean addDept(@RequestBody Dept dept) {
        return deptService.addDept(dept);
    }

    @HystrixCommand(fallbackMethod = "HystrixQueryById")//开启服务熔断 指定熔断方法
    //当服务出现问题之后 例如：抛出异常 则会转而执行熔断方法 而不是返回xxx错误信息页面给客户端
    @GetMapping("/get/{id}")
    public Dept queryById(@PathVariable("id") Long id) {
        Dept dept = deptService.queryById(id);
        if (ObjectUtils.isEmpty(dept)) {
            throw new RuntimeException("服务熔断");
        }
        return dept;
    }

    public Dept HystrixQueryById(@PathVariable("id") Long id) {
        return new Dept().setDeptno(1L).setDb_source("Mysql Exception").setDname("id" + id + "异常 ----- @Hystrix");
    }

    @GetMapping("/list")
    public List<Dept> queryAll() {
        return deptService.queryAll();
    }


    //获取eureka一些消息
    @GetMapping("/discovery")
    public void discovery() {
        //获得微服务列表清单
        List<String> services = client.getServices();
        System.out.println(services);
        //通过id得到一个具体的微服务
        List<ServiceInstance> instances = client.getInstances("");
        for (ServiceInstance instanceInfo : instances) {
            System.out.println(instanceInfo.getPort());
        }
    }

}
